import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin } from 'antd';
import { DATA_ENTRY, AdvancedSearch, ModalC, ContentPackage, TableC } from '../../../comps';
import myStyle from './index.less';
import MyModal from './myModal';

@connect(({ monitoringM, loading }) => ({
  monitoringM,
  loading,
}))
@Form.create()
export default class LimitMonitoring extends PureComponent {
  state = {
    visible: false, //模态框显示与否
    modalData: {}, //详情页数据
    searchForm: {}, //搜索条件
    productCode: '', //产品的code
    timeOutGap: 500,
    collapsed: undefined,
    userViewType: undefined, // 用户视图跳转
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.props.dispatch({
      type: 'monitoringM/save',
      payload: {
        isLoading: true,
      },
    });

    this.riskSearch(); //查询风控条目下拉列表
    // 适配用户视图跳转至,定位指定的产品、日期
    if (!!sessionStorage.getItem('jumpInfo')) {
      const obj = JSON.parse(sessionStorage.getItem('jumpInfo'));
      if (obj.type == '16' || obj.type == '17') {
        this.setState({
          userViewType: obj.type,
        });
        sessionStorage.removeItem('jumpInfo');
      }
    }
    this.queryTableList();
    this.timer = setInterval(() => {
      //每5s请求一次
      this.queryTableList();
    }, 5000);
  }
  componentWillUnmount() {
    //离开前清除掉定时器
    this.timer && clearInterval(this.timer);
    this.timer = null;
    this.props.dispatch({
      type: 'monitoringM/save',
      payload: {
        selectData: [],
        tableDataObj: {}, //列表数据
        detailData: [],
        isLoading: false, //第一次点击查询按钮有loading效果
      },
    });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.nowKey != this.props.nowKey) {
      if (nextProps.nowKey == true && !this.timer) {
        this.queryTableList('first');
        this.timer = setInterval(() => {
          this.queryTableList();
        }, 5000);
      } else if (nextProps.nowKey == false) {
        //离开前清除掉定时器
        this.timer && clearInterval(this.timer);
        this.timer = null;
      }
    }
    if (!!sessionStorage.getItem('jumpInfo')) {
      const obj = JSON.parse(sessionStorage.getItem('jumpInfo'));
      if (obj.type == '16' || obj.type == '17') {
        this.setState({
          userViewType: obj.type,
        });
        sessionStorage.removeItem('jumpInfo');
      }
    }
  }

  //查询表格数据
  queryTableList = (type) => {
    const { dispatch } = this.props;
    const { searchForm } = this.state;

    dispatch({
      type: 'monitoringM/getTableDta',
      payload: {
        ...searchForm,
        currentPage: 1,
        numInPage: 999,
        type: type == 'first' ? type : '',
      },
    });
  };
  //展示表格
  showTable = () => {
    const {
      monitoringM: {
        isLoading,
        tableDataObj: { columns = [], dataSource = [] },
      },
    } = this.props;
    const currentHeight = document.getElementById('tabDiyWidth') ? document.getElementById('tabDiyWidth').offsetHeight - 228 : '100%';
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        key: 'operate',
        width: 55,
        render: (text, record) => {
          return <a onClick={() => this.showInfo(record)}>详细 </a>;
        },
      });
    }
    columns.map((item) => {
      if (item.key != 'ruleNo' && item.key != 'ruleDesc' && item.key != 'operate') {
        item.align = 'right';
        item.width = 150;
        item.render = (text, record) => {
          if (record.pecent === false) {
            return text !== null ? text : '--';
          } else {
            return text !== null ? parseFloat(text * 100).toFixed(2) + '%' : '--';
          }
        };
      }
      if (item.key == 'ruleDesc') {
        item.ellipsis = true;
      }
      if (item.key == 'ruleNo') {
        item.width = 120;
      }
    });
    let dataSourceNew = [];
    if (this.state.userViewType) {
      dataSource.map((item) => {
        if (this.state.userViewType == '16') {
          if (item.marginValue < 0 && (!!item.warningValue || item.warningValue == 0)) {
            dataSourceNew.push(item);
          }
        }
        if (this.state.userViewType == '17') {
          if (item.marginValue < 0 && (!!item.prohibitValue || item.prohibitValue == 0)) {
            dataSourceNew.push(item);
          }
        }
      });
    }
    return (
      <div>
        <TableC
          loading={isLoading}
          columns={columns}
          dataSource={this.state.userViewType ? dataSourceNew : dataSource}
          rowKey='ruleNo'
          scroll={{ x: '100%' }}
          hidePage={true}
          selfScrollY={true}
        />
      </div>
    );
  };
  //查询详情页信息 弹出模态框
  showInfo = (e) => {
    const { dispatch } = this.props;
    this.setState({
      visible: true,
      record: e,
      timeStamp: new Date().getTime(),
    });
  };
  //风控条目下拉
  riskSearch = (e) => {
    const tenant = localStorage.getItem('antd-pro-tenant');
    const { dispatch } = this.props;
    dispatch({
      type: 'monitoringM/getSelectData',
      payload: {
        pageNumber: 1,
        pageSize: 999,
        ruleDesc: e,
        tenant: tenant,
      },
    });
  };

  showModal = () => {
    const props = {
      visible: this.state.visible,
      onOk: () => {
        this.setState({ visible: false });
      },
      onCancel: () => {
        this.setState({ visible: false });
      },
      title: '限额详情',
      className: 'limitDetail',
      footer: null,
      height: 500,
    };
    return (
      <div>
        <ModalC {...props}>
          <MyModal record={this.state.record} timeStamp={this.state.timeStamp} modalData={this.state.modalData} />
        </ModalC>
      </div>
    );
  };

  render() {
    const {
      monitoringM: { selectData, tableDataObj },
    } = this.props;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'productCodeList',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          multiple: true,
          onChange: (e) => {
            //取产品的code 传给后台
            if (!e) {
              this.setState({
                productCode: '',
              });
              return;
            }
            const arr = e.info.map((item) => {
              return item.portfolioCode;
            });
            this.setState({
              productCode: arr.length ? arr.join(',') : '',
            });
          },
        },
        {
          dataIndex: 'ruleId',
          title: '风控条目',
          type: DATA_ENTRY.SELECT,
          dataSource: selectData,
          filterOption: false,
          allowClear: true,
          // onSearch: (e) => { this.riskSearch(e) },
          filterOption: (
            input,
            option, //模糊搜索value 和 title
          ) => {
            return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
          },
          disabled: this.state.flag,
          optionTitle: true,
        },
      ],
      onQuery: (e) => {
        e.productCodeList = this.state.productCode;
        this.setState(
          {
            searchForm: e,
            userViewType: undefined,
          },
          () => {
            this.timer && clearInterval(this.timer);
            this.timer = null;
            tableDataObj.dataSource = [];
            this.props.dispatch({
              type: 'monitoringM/save',
              payload: {
                tableDataObj,
                isLoading: true,
              },
            });
            this.props.dispatch({
              type: 'monitoringM/runAll',
              payload: {},
            });
            this.queryTableList('first');
            this.timer = setInterval(() => {
              this.queryTableList();
            }, 5000);
          },
        );
      },
      onClear: () => {
        this.setState(
          {
            searchForm: {},
            productCode: '',
            userViewType: undefined,
          },
          () => {
            this.timer && clearInterval(this.timer);
            this.timer = null;
            tableDataObj.dataSource = [];
            this.props.dispatch({
              type: 'monitoringM/save',
              payload: {
                tableDataObj,
              },
            });

            this.queryTableList('first');
            this.timer = setInterval(() => {
              this.queryTableList();
            }, 5000);
          },
        );
      },
    };
    return (
      <ContentPackage
        title='限额监控'
        contentHtml={
          <div>
            <div>
              <div className={myStyle.LimitMonitoring}>
                <div className={'cardBody'}>
                  <AdvancedSearch {...searchProps} />
                </div>
                {this.showTable()}
              </div>
            </div>
            {this.state.visible && this.showModal()}
          </div>
        }
      />
    );
  }
}
